package com.tz.online.user.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.tz.online.entity.User;
import com.tz.online.user.dao.IUserDao;
import com.tz.online.util.JdbcUtils;

public class UserDaoImpl implements IUserDao {

	@Override
	public User selectUserByName(String name) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;

		// 创建一个用户对象
		User user = null;

		try {
			// 2.获取数据库连接
			conn = JdbcUtils.getConnection();
			// 3.创建语句对象
			st = conn.createStatement();
			// 执行SQL
			String sql = "select * from online_user where  username='" + name
					+ "'";
			rs = st.executeQuery(sql);
			// 处理结果
			if (rs.next()) {
				user = new User();
				long userid = rs.getLong(1);
				String address = rs.getString(2);
				String comparate = rs.getString(3);
				String email = rs.getString(4);
				String password = rs.getString(5);
				String tel = rs.getString(6);
				String username = rs.getString(7);

				// 封装数据
				user.setUserId(userid);
				user.setUsername(username);
				user.setPassword(password);
				user.setTel(tel);
				user.setEmail(email);
				user.setAddress(address);
				user.setComparate(comparate);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 6.释放资源
			JdbcUtils.closeResources(conn, st, rs);
		}
		/*
		 * try { ses = HibernateUtil.getSession(); tr = ses.getTransaction();
		 * tr.begin(); String hql = "from User u where u.username=:name"; user =
		 * (User)ses.createQuery(hql).setString("name", name) .uniqueResult();
		 * tr.commit(); } catch (Exception e) { // TODO Auto-generated catch
		 * block e.printStackTrace(); }finally{
		 * 
		 * if(ses != null){ ses.close(); } }
		 */
		return user;
	}

	@Override
	public void insertUser(User user) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;

		try {
			conn = JdbcUtils.getConnection();
			// 3.创建语句对象
			st = conn.createStatement();

			String sql = "insert into online_user (address,comparate,email,password,tel,username) values ('"
					+ user.getAddress()
					+ "','"
					+ user.getComparate()
					+ "','"
					+ user.getEmail()
					+ "','"
					+ user.getPassword()
					+ "','"
					+ user.getTel() + "','" + user.getUsername() + "')";
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 6.释放资源
			JdbcUtils.closeResources(conn, st, rs);
		}

		/*
		 * Session ses = null; Transaction tr = null;
		 * 
		 * try { ses = HibernateUtil.getSession(); tr = ses.getTransaction();
		 * tr.begin(); ses.saveOrUpdate(user); tr.commit(); } catch (Exception
		 * e) { // TODO Auto-generated catch block e.printStackTrace(); }
		 * finally {
		 * 
		 * if (ses != null) { ses.close(); } } }
		 */
	}

}
